import logging
import os
from functools import wraps
from flask import session, request, render_template, redirect, url_for
from leancloud import Query, LeanCloudError
from dbModels import WechatUser

ISLOCAL = os.environ.get('VIRTUAL_ENV', '').startswith('F:')
if not ISLOCAL:
    ISLOCAL = os.environ.get('VIRTUAL_ENV', '') == '/home/imfun/Program/venv/leancloud'
if not ISLOCAL:
    ISLOCAL = os.environ.get('LC_LOCAL', '') == 'True'

def wxauth(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        code = request.args.get('code')
        if code:
            try:
                from wechatAPI import getauth
                openid = getauth(code)
                session['openid'] = openid
                if not openid:
                    logging.error('WxAuthGetOpenidWithCode CodeFaild:%s' % request.url)
            except:
                logging.error('WxAuthGetOpenidWithCode Faild:%s' % request.url)
        return func(*args, **kwargs)

    return wrapper
    
def wxauth_redirect(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        code = request.args.get('code')
        if code:
            try:
                from wechatAPI import getauth
                openid = getauth(code)
                session['openid'] = openid
            except:
                logging.error('WxAuthGetOpenidWithCodeRedirect Faild:%s' % request.url)
            return func(*args, **kwargs)
        else:
            from wechatAPI import getauthurl
            re_url = getauthurl(request.url)
            return redirect(re_url)
    return wrapper
    
def wxauth_permission(role='agmadmin'):
    def outer_wraps(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            if ISLOCAL:
                return func(*args, **kwargs)
            session.permanent = True
            code = request.args.get('code')
            if code:
                code = request.args.getlist('code')[-1]
                from wechatAPI import getauth
                openid = getauth(code)
                if openid:
                    session['openid'] = openid
                else:
                    session['getopeniderror'] = session.get('getopeniderror', 0) + 1
                    logging.error('(%s)WxAuthGetOpenidWithCodeRedirect Faild:%s' % (session.get('getopeniderror', 0), request.url))
            openid = session.get('openid')
            if openid:           
                try:
                    if isinstance(role, list):
                        wechatuser = Query(WechatUser).equal_to('openid', openid).contained_in('role', role).first()
                    elif role is None:
                        wechatuser = Query(WechatUser).equal_to('openid', openid).first()
                    elif role == -1:
                        wechatuser = Query(WechatUser).equal_to('openid', openid).find()
                        if wechatuser:
                            session['wechatuserid'] = wechatuser[0].id
                            if wechatuser[0].get('role'):
                                session['wechatrole'] = wechatuser[0].get('role')
                            else:
                                session.pop('wechatrole', None)  
                        return func(*args, **kwargs)
                    else:
                        wechatuser = Query(WechatUser).equal_to('openid', openid).equal_to('role', role).first()
                    session['wechatuserid'] = wechatuser.id
                    if wechatuser.get('role'):
                        session['wechatrole'] = wechatuser.get('role') 
                    else:
                        session.pop('wechatrole', None)                        
                    return func(*args, **kwargs)
                except LeanCloudError:
                    return render_template('agm1.0/agm_wx_deny.html')
            else:
                if request.headers.get('User-Agent') and 'MicroMessenger/' in request.headers.get('User-Agent') and not session.get('getopeniderror', 0) > 3:
                    from wechatAPI import getauthurl
                    re_url = getauthurl(request.url)
                    return '<script>location.href="%s"</script>' % re_url
                else:
                    return render_template('agm1.0/agm_wx_deny.html')
        return wrapper
    return outer_wraps
    
def wxauth_permission_login(role='agmadmin'):
    def outer_wraps(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            # session.permanent = True
            code = request.args.get('code')
            if code and not session.get('openid'):
                code = request.args.getlist('code')[-1]
                from wechatAPI import getauth
                openid = getauth(code)
                if openid:
                    session.permanent = True
                    session['openid'] = openid
                else:
                    session['getopeniderror'] = session.get('getopeniderror', 0) + 1
                    logging.error('(%s)WxAuthGetOpenidWithCodeRedirect Faild:%s' % (session.get('getopeniderror', 0), request.url))
            openid = session.get('openid')
            # if ISLOCAL:
                # return func(*args, **kwargs)
            if openid:           
                try:
                    if isinstance(role, list):
                        wechatuser = Query(WechatUser).equal_to('openid', openid).contained_in('role', role).first()
                    elif role is None:
                        wechatuser = Query(WechatUser).equal_to('openid', openid).first()
                    elif role == -1:
                        wechatuser = Query(WechatUser).equal_to('openid', openid).find()
                        if wechatuser:
                            session['wechatuserid'] = wechatuser[0].id
                            if wechatuser[0].get('role'):
                                session['wechatrole'] = wechatuser[0].get('role')
                            else:
                                session.pop('wechatrole', None)  
                        return func(*args, **kwargs)
                    else:
                        wechatuser = Query(WechatUser).equal_to('openid', openid).equal_to('role', role).first()
                    session['wechatuserid'] = wechatuser.id
                    if wechatuser.get('role'):
                        session['wechatrole'] = wechatuser.get('role') 
                    else:
                        session.pop('wechatrole', None)                        
                    return func(*args, **kwargs)
                except LeanCloudError:
                    if checklogin(role):
                        return func(*args, **kwargs)
                    return redirect(url_for('agmadmin.wraplogin', next=request.full_path))
                    # return render_template('agm1.0/agm_wx_deny.html')
            else:
                if request.headers.get('User-Agent') and 'MicroMessenger/' in request.headers.get('User-Agent') and not session.get('getopeniderror', 0) > 3:
                    from wechatAPI import getauthurl
                    re_url = getauthurl(request.url)
                    return '<script>location.href="%s"</script>' % re_url
                else:
                    if checklogin(role):
                        return func(*args, **kwargs)
                    return redirect(url_for('agmadmin.wraplogin', next=request.full_path))                    
                    # return render_template('agm1.0/agm_wx_deny.html')
        return wrapper
    return outer_wraps    
    
def checklogin(role):
    role0 = session.get('role')
    if isinstance(role, list):
        return role0 in role
    return role0 == role if role else True


    
    
